<template>
    <el-form ref="ruleFormRef" :model="formData" :rules="formRules" size="small" :inline="false" label-width="100px">
      <el-form-item label="主题" prop="title">
        <el-input v-model="formData.title" placeholder="请填写主题" maxlength="32" size="small"/>
      </el-form-item>
      <el-form-item label="员工" prop="staffId">
        <el-select v-model="formData.staffId" placeholder="请选择员工" size="small" filterable>
          <el-option v-for="item in staffList" :key="item.id" :value="item.id" :label="item.name"/>
        </el-select>
      </el-form-item>
      <el-form-item label="计划离职日期" prop="occurDate">
        <el-date-picker value-format="YYYY-MM-DD" format="YYYY-MM-DD" v-model="formData.occurDate" type="datetime" placeholder="请选择计划离职日期" size="small"/>
      </el-form-item>
      <el-form-item label="薪资结算日期" prop="settlementDate">
        <el-date-picker value-format="YYYY-MM-DD" format="YYYY-MM-DD" v-model="formData.settlementDate" type="datetime" placeholder="请选择薪资结算日期" size="small"/>
      </el-form-item>
      <el-form-item label="离职类型" prop="staffLeaveType">
        <el-select v-model="formData.staffLeaveType" placeholder="请选择离职类型" size="small">
          <el-option v-for="item in dictMap['LeaveOfficeType']" :key="item.value" :value="item.value" :label="item.name"/>
        </el-select>
      </el-form-item>
      <el-form-item label="离职原因" prop="content">
        <editor v-model="formData.content"/>
      </el-form-item>
      <el-form-item label="优先度" prop="priority">
        <el-radio-group v-model="formData.priority" size="small">
          <el-radio :label="0" size="small">普通</el-radio>
          <el-radio :label="1" size="small">高</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注信息" prop="remark">
        <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请填写备注信息" size="small"/>
      </el-form-item>
    </el-form>
</template>

<script>
// 离职申请 OA_APPLY_QUIT
import { onMounted, reactive, toRefs, computed, watch, nextTick, ref } from 'vue'
import {getDictByCodes} from '/@/api/sys/dict'
import {listByState} from '/@/api/oa/staff'
import {homeApi} from '/@/api/home/index'
import Editor from '/@/components/editor/index.vue'
import { useCalendarConfig } from '/@/stores/calendar';
import { storeToRefs } from 'pinia';
export default {
    name: 'DimissionApplyForm',
    components: {
        Editor
    },
    props: {
      selectTime: {
        type: String,
        default: null
      },
      editId: {
        type: String,
        default: null
      }
    },
    setup(props, context) {
        const { editId, selectTime } = toRefs(props)
        const homeCalendar = homeApi()
        const ruleFormRef = ref({})
        const storesCalendarConfig = useCalendarConfig();
        const { eventForm } = storeToRefs(storesCalendarConfig)
        const getSelected = computed(() => {
          if(selectTime.value) {
            return selectTime.value.substring(0,10)
          }
          return null
        })
        const state = reactive({
            code: '',
            formData: {
                title: '离职申请',
                staffId: null,
                content: null,    // 离职原因
                occurDate: getSelected.value,    // 离职申请时间
                settlementDate: null,   // 薪资结算时间
                staffLeaveType: null,   // 离职类型
                remark: null,   // 备注信息
                state: 2,           // 状态 -1草稿 0未开始 1进行中 2已完成 3已退回  4已取消 5已撤回
                priority: 0        // 优先级 0普通 1重要
            },
            formRules: {
                title: {required: true, message: '请填写主题', trigger: 'blur'},
                staffId: {required: true, message: '请选择员工', trigger: 'change'},
                content: {required: true, message: '请填写离职原因', trigger: 'blur'},
                occurDate: {required: true, message: '请选择离职申请日期', trigger: 'change'},
                settlementDate: {required: true, message: '请选择薪资结算时间', trigger: 'change'},
                staffLeaveType: {required: true, message: '请选择离职类型', trigger: 'change'}
            },
            dictMap: {},
            staffList: [],
            originForm: {}
        })
        // 提交事件
        const submit = () => {
          if (!ruleFormRef) return
          return new Promise(async (resolve, reject) => {
            await ruleFormRef.value.validate((valid, fields) => {
              if(valid) {
                if(editId.value) {
                  // 编辑
                  for(let key in state.formData){
                    if(state.originForm.hasOwnProperty(key)){
                      state.originForm[key] = state.formData[key]
                    }
                    if(state.originForm.info.hasOwnProperty(key)){
                      state.originForm.info[key] = state.formData[key]
                    }
                  }
                  storesCalendarConfig.setEventForm(state.originForm)
                  resolve('edit') 
                }else{
                   homeCalendar
                    .addApplyQuit(state.formData)
                    .then((res) => {
                        if (res.code === 0) {
                          reset()
                          // ElMessage.success('提交成功！')
                          context.emit('closeForm')
                          resolve()
                        }
                    })
                    .catch(e => reject(e))
                }
              }else {
                console.log('error submit!', fields)
              }
            })
           
          })
        }
        // 清空表单
        const reset = () => {
          if (!ruleFormRef) return
          ruleFormRef.value.resetFields()
        }
        watch(() => eventForm.value,
          val => {
            if(editId.value && val) {
              // 编辑
              nextTick(() => {
                const data = val
                if(!data) return
                state.originForm = data
                for(let params in data.info){
                  // 拿出info里面的数据
                  if(state.formData.hasOwnProperty(params)) {
                    state.formData[params] = data.info[params]
                  }
                }
                for(let key in data) {
                  // 列表里面的数据
                  if(state.formData.hasOwnProperty(key)) {
                    state.formData[key]= data[key]
                  }
                }
              })
            }
          }        
        )
        onMounted(async () => {
            const dictData = await getDictByCodes(['LeaveOfficeType'])
            state.dictMap = dictData.data
            const staffData = await listByState('')
            state.staffList = staffData.data
        })
        return {
            ...toRefs(state),
            submit,
            reset,
            ruleFormRef
        }
    }
}
</script>

<style>

</style>